package com.kele.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * @author kele
 * @date 2021/10/13 17:59
 * @description
 * 原子引用，解决ABA问题
 */
public class ABADeal {

    public static void main(String[] args) {

        AtomicStampedReference<Integer> atomicInteger=new AtomicStampedReference(1,1);

        new Thread(()->{
            /**
             * 获得版本号
             */
            int stamp = atomicInteger.getStamp();
            System.out.println("A1版本号是 : "+stamp);
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(atomicInteger.compareAndSet(1, 2, atomicInteger.getStamp(), atomicInteger.getStamp() + 1));

            System.out.println("A2的版本号是 : "+atomicInteger.getStamp());

            System.out.println(atomicInteger.compareAndSet(2, 1, atomicInteger.getStamp(), atomicInteger.getStamp() + 1));

            System.out.println("A3的版本号是 : "+atomicInteger.getStamp());
        },"A").start();

        new Thread(()->{
            int stamp = atomicInteger.getStamp();
            System.out.println("B1版本号是 : "+stamp);

            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            System.out.println(atomicInteger.compareAndSet(1, 6666, stamp, stamp + 1));
            System.out.println("B2版本号是 : "+atomicInteger.getStamp());
        },"B").start();
    }
}
